package handler

import (
	"demo/internal/config"
	"demo/internal/model"
	"demo/internal/service"
	"demo/pkg/response"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

type AccountHandler struct {
	svc    *service.UserService
	config *config.Config
}

func NewAccountHandler(svc *service.UserService, cfg *config.Config) *AccountHandler {
	return &AccountHandler{
		svc:    svc,
		config: cfg,
	}
}

// @Summary		注册新用户
// @Description	注册新用户账号
// @Tags			账户管理
// @Accept			json
// @Produce		json
// @Param			user	body		model.User	true	"用户注册信息"
// @Success		200		{object}	response.Response	"注册成功"
// @Failure		400		{object}	response.Response	"参数错误"
// @Failure		500		{object}	response.Response	"服务器内部错误"
// @Router			/signup [post]
func (h *AccountHandler) SignUp(c *gin.Context) {
	var u model.User
	if err := c.ShouldBindJSON(&u); err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	if err := h.svc.Register(&u); err != nil {
		response.InternalServerError(c, err.Error())
		return
	}
	response.Success(c, nil, "User registered successfully")
}

// @Summary		用户登录
// @Description	用户登录并获取JWT令牌
// @Tags			账户管理
// @Accept			json
// @Produce		json
// @Param			credentials	body		object{username=string,password=string}	true	"用户登录凭证"
// @Success		200			{object}	response.Response{data=object{token=string}}	"登录成功"
// @Failure		400			{object}	response.Response	"参数错误"
// @Failure		401			{object}	response.Response	"认证失败"
// @Router			/login [post]
func (h *AccountHandler) Login(c *gin.Context) {
	var creds struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}
	if err := c.ShouldBindJSON(&creds); err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	user, err := h.svc.Login(creds.Username, creds.Password)
	if err != nil {
		response.Unauthorized(c, "用户名或密码错误")
		return
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": user.Username,
		"exp":      time.Now().Add(24 * time.Hour).Unix(),
	})
	tokenString, err := token.SignedString([]byte(h.config.JWT.Secret))
	if err != nil {
		response.InternalServerError(c, "Token generation failed")
		return
	}
	response.Success(c, gin.H{"token": tokenString}, "Login successful")
}

// @Summary		获取用户信息
// @Description	获取当前登录用户的个人信息
// @Tags			账户管理
// @Accept			json
// @Produce		json
// @Success		200	{object}	response.Response{data=object{username=string}}	"获取成功"
// @Failure		401	{object}	response.Response	"未授权"
// @Router			/api/profile [get]
// @Security		BearerAuth
func (h *AccountHandler) Profile(c *gin.Context) {
	claims := c.MustGet("claims").(jwt.MapClaims)
	username := claims["username"].(string)
	response.Success(c, gin.H{"username": username}, "Profile retrieved successfully")
}
